Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5,
with the first five elements of nums being 1, 1, 2, 2 and 3.
It doesn't matter what you leave beyond the new length.
题目大意:给定一个已经排好序的数组,去重,每个数字至多出现2次,返回去重后数组的长度,去重在原数组上进行。
题目难度:Medium
/**
* Created by gzdaijie on 16/6/4
* 使用isDup记录是否新加的数已经出现过
* 空间复杂度O(1),时间复杂度O(N)
*/
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length < 3) return nums.length;
int k = 0;
int last = nums[0];
boolean isDup = false;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != last) {
nums[++k] = last = nums[i];
isDup = false;
continue;
}
if (isDup) continue;
nums[++k] = last;
isDup = true;
}
return k + 1;
}
}